<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form class="verify-form" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="商品类别" prop="ctgId">
        <el-select v-model="dataForm.ctgId" placeholder="请选择" @change="getSupplyList">
          <el-option v-for="item in ctgIdOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="制造商" prop="supplyId">
        <el-select v-model="dataForm.supplyId" placeholder="请选择" @change="getBrandList">
          <el-option v-for="item in supplyOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品品种" prop="brandId">
        <el-select v-model="dataForm.brandId" placeholder="请选择" @change="getGoodsNameList">
          <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsId">
        <el-select v-model="dataForm.goodsId" placeholder="请选择">
          <el-option v-for="item in goodsNameOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与活动门店" prop="deptIds">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="dataForm.deptIds" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="dept in deptOptions" :label="dept.value" :key="dept.value">{{dept.label}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="卡类型" prop="cardType">
        <el-radio v-model="dataForm.cardType" :label="0">非会员卡</el-radio>
        <el-radio v-model="dataForm.cardType" :label="1">会员卡</el-radio>
        <el-radio v-model="dataForm.cardType" :label="2">所有类型卡</el-radio>
      </el-form-item>
      <el-form-item label="1元兑换积分比例" prop="exchangeRate">
        <el-input v-model="dataForm.exchangeRate" placeholder="1元兑换积分比例"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input v-model="dataForm.memo" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { getObj, addObj, putObj } from "@/api/eims/integralrule";
  import { fetchCtgSaleList } from "@/api/eims/ctg";
  import { fetchSupplyList } from '@/api/eims/supply'
  import { fetchBrandList } from '@/api/eims/brand'
  import { goodsFetchList } from '@/api/eims/goods'
  import { getDeptInfoByDeptType } from '@/api/admin/dept'

  export default {
    data() {
      var exchangeRateCheck = (rule, value, callback) => {
        let numPattern = /^-?\d*\.?\d+$/
        if (!numPattern.test(value)) {
          callback(new Error("请输入纯数字"));
        } else {
          callback()
        }
      };
      return {
				ischeck: false,
        visible: false,
        ctgIdOptions: [],
        supplyOptions: [],
        brandOptions: [],
        goodsNameOptions: [],
        isIndeterminate: false,
        checkAll: false,
        deptOptions: [],
        dataForm: {
          id: 0,
          ctgId: "",
          supplyId: "",
          brandId: "",
          goodsId: "",
          deptIds: [],
          cardType: "",
          exchangeRate: "",
          memo: ""
        },
        dataRule: {
          ctgId: [{
            required: true,
            message: "商品类别id不能为空",
            trigger: "blur"
          }],
          cardType: [{
            required: true,
            message: "卡类型不能为空",
            trigger: "blur"
          }],
          exchangeRate: [{
              required: true,
              message: "1元兑换积分比例不能为空",
              trigger: "blur"
            },
            {
              validator: exchangeRateCheck
            }
          ]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0;
        this.visible = true;
        this.$nextTick(() => {
          this.getDataList();
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            getObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
              	if (response.data.data.ctgId) {
              	  this.getSupplyList()
              	}
              	if (response.data.data.supplyId) {
              	  this.getBrandList()
              	}
              	if (response.data.data.brandId) {
              	  this.getGoodsNameList()
              	}
              	this.dataForm = response.data.data
              }else{
              	this.$message.error(response.data.msg)
              }
            })
          }
        });
      },
      // 表单提交
      dataFormSubmit() {
				this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            if (this.dataForm.id) {
              putObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                	this.$message.success("修改成功")
                	this.visible = false
                	this.$emit("refreshDataList")
                }else{
                	this.$message.error(response.data.msg)
                }
								this.ischeck = false
              }).catch(() => {
								this.ischeck = false
							})
            } else {
              addObj(this.dataForm).then(response => {
								if(response.data.code == '0'){
									this.$message.success("添加成功")
									this.visible = false
									this.supplyOptions = []
									this.brandOptions = []
									this.goodsNameOptions = []
									this.$emit("refreshDataList")
								}else{
									this.$message.error(response.data.msg)
								}
								this.ischeck = false
              }).catch(() => {
								this.ischeck = false
							})
            }
          }else{
						this.ischeck = false
					}
        });
      },
      //取消按钮
      cancel() {
        this.visible = false;
        this.supplyOptions = [];
        this.brandOptions = [];
        this.goodsNameOptions = [];
      },
      getDataList() {
        fetchCtgSaleList({type: 3}).then(response => {
          if(response.data.code == '0'){
          	let result = response.data.data
          	let list = []
          	result.forEach(item => {
          	  list.push({
          	    value: item.id,
          	    label: item.name
          	  })
          	})
          	this.ctgIdOptions = list
          }else{
          	this.$message.error(response.data.msg)
          }
        });
      },
      getSupplyList(val) {
        this.dataForm.supplyId = ''
        this.dataForm.brandId = ''
        this.dataForm.goodsId = ''
        this.supplyOptions = [];
        this.brandOptions = [];
        this.goodsNameOptions = [];
        let params = {
          current: 1,
          size: 100000,
          ctgId: val
        }
        fetchSupplyList(params).then(response => {
          if(response.data.code == '0'){
          	let resultData = response.data.data.records
          	let list = []
          	resultData.forEach(item => {
          	  list.push({
          	    value: item.id,
          	    label: item.name
          	  })
          	})
          	this.supplyOptions = list
          }else{
          	this.$message.error(response.data.msg)
          }
        })
      },
      getBrandList(val) {
        this.dataForm.brandId = ''
        this.dataForm.goodsId = ''
        this.brandOptions = [];
        this.goodsNameOptions = [];
        let params = {
          current: 1,
          size: 100000,
          supplyId: val
        }
        fetchBrandList(params).then(response => {
          if(response.data.code == '0'){
          	let resultData = response.data.data.records
          	let list = []
          	resultData.forEach(item => {
          	  list.push({
          	    value: item.id,
          	    label: item.name
          	  })
          	})
          	this.brandOptions = list
          }else{
          	this.$message.error(response.data.msg)
          }
        })
      },
      getGoodsNameList(val) {
        this.dataForm.goodsId = ''
        this.goodsNameOptions = [];
        let params = {
          current: 1,
          size: 100000,
          brandId: val
        }
        goodsFetchList(params).then(response => {
          if(response.data.code == '0'){
          	let resultData = response.data.data.records;
          	let list = [];
          	resultData.forEach(item => {
          	  list.push({
          	    value: item.id,
          	    label: item.name
          	  });
          	});
          	this.goodsNameOptions = list;
          }else{
          	this.$message.error(response.data.msg)
          }
        })
      },
      getList() {
        getDeptInfoByDeptType(1).then(response => {
          if(response.data.code == '0'){
          	let result = response.data.data
          	let list = []
          	result.forEach(item => {
          	  list.push({
          	    value: item.id,
          	    label: item.name
          	  })
          	})
          	this.deptOptions = list
          }else{
          	this.$message.error(response.data.msg)
          }
        })
      },
      handleCheckAllChange(val) {
        if (val) {
          this.deptOptions.forEach(item => {
            this.dataForm.deptIds.push(item.value);
          });
        } else {
          this.dataForm.deptIds = [];
        }
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.deptOptions.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.deptOptions.length;
      }
    }
  };
</script>
